/*
 * Zirco Browser for Android
 * 
 * Copyright (C) 2010 J. Devauchelle and contributors.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * version 3 as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 */

package org.xtown.bingluo.xtieba.utils;

import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.xtown.bingluo.xtieba.R;
import org.xtown.bingluo.xtieba.standby.Constants;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;

/**
 * Utilities for I/O reading and writing.
 */
public class IOUtils {

	private static final String APPLICATION_FOLDER = "zirco";
	private static final String DOWNLOAD_FOLDER = "downloads";
	private static final String BOOKMARKS_EXPORT_FOLDER = "bookmarks-exports";
	private static String TAG = "IOUtils";

	/**
	 * Get the application folder on the SD Card. Create it if not present.
	 * 
	 * @return The application folder.
	 */
	public static File getApplicationFolder() {
		File root = Environment.getExternalStorageDirectory();
		if (root.canWrite()) {

			File folder = new File(root, APPLICATION_FOLDER);

			if (!folder.exists()) {
				folder.mkdir();
			}

			return folder;

		} else {
			return null;
		}
	}

	/**
	 * Get the application download folder on the SD Card. Create it if not
	 * present.
	 * 
	 * @return The application download folder.
	 */
	public static File getDownloadFolder() {
		File root = getApplicationFolder();

		if (root != null) {

			File folder = new File(root, DOWNLOAD_FOLDER);

			if (!folder.exists()) {
				folder.mkdir();
			}

			return folder;

		} else {
			return null;
		}
	}

	/**
	 * Get the application folder for bookmarks export. Create it if not
	 * present.
	 * 
	 * @return The application folder for bookmarks export.
	 */
	public static File getBookmarksExportFolder() {
		File root = getApplicationFolder();

		if (root != null) {

			File folder = new File(root, BOOKMARKS_EXPORT_FOLDER);

			if (!folder.exists()) {
				folder.mkdir();
			}

			return folder;

		} else {
			return null;
		}
	}

	/**
	 * Get the list of xml files in the bookmark export folder.
	 * 
	 * @return The list of xml files in the bookmark export folder.
	 */
	public static List<String> getExportedBookmarksFileList() {
		List<String> result = new ArrayList<String>();

		File folder = getBookmarksExportFolder();

		if (folder != null) {

			FileFilter filter = new FileFilter() {

				@Override
				public boolean accept(File pathname) {
					if ((pathname.isFile())
							&& (pathname.getPath().endsWith(".xml"))) {
						return true;
					}
					return false;
				}
			};

			File[] files = folder.listFiles(filter);

			for (File file : files) {
				result.add(file.getName());
			}
		}

		Collections.sort(result, new Comparator<String>() {

			@Override
			public int compare(String arg0, String arg1) {
				return arg1.compareTo(arg0);
			}
		});

		return result;
	}

	public static String getAppRootPath(Context c) {
		String p ="";
		if (!android.os.Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED)) {
			p = c.getFilesDir() + Constants.APP_ROOT_PATH;
		} else {
			if (getSDPath() != null) {
				p = getSDPath() + Constants.APP_ROOT_PATH;
			}
		}
		return p;
	}
	public static String getSDPath() {
		File sdDir = null;
		// 判断sd卡是否存在
		boolean sdCardExist = Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED);
		if (sdCardExist) {
			// 获取根目录
			sdDir = Environment.getExternalStorageDirectory();
		}
		return sdDir.toString();
	}
	
	public static String getAvatarPath(Context c) {
		return getAppRootPath(c) + Constants.AVATAR_PATH;
	}
	public static String getAvatarPathInSd(Context c) {
		String p = "";
		if (getSDPath() != null) {
			p = getSDPath() + Constants.APP_ROOT_PATH + Constants.AVATAR_PATH;
		}
		return p;
	}
	public static String getAvatarPathInFiles(Context c) {
		return c.getFilesDir() + Constants.APP_ROOT_PATH + Constants.AVATAR_PATH;
	}

	public static Bitmap getBitmapFromFilePath(String path) {
		Bitmap bm = null;
		FileInputStream inputStream = null;
		File f = null;
		try {
			f = new File(path);
			if (f.exists() && f.isFile() && f.canRead()) {
				inputStream = new FileInputStream(f);
				try {
					if (inputStream != null && inputStream.available() > 0) {
						bm = BitmapFactory.decodeStream(inputStream);
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		}

		return bm;
	}

	public static Bitmap getBitmapFromUrl(Context c, String url, String toPath) {
		Bitmap bm = null;
		url = UrlUtils.checkUrl(url);
		LogUtlils.println(url);
		NetUtils net = new NetUtils(c);
		net.openConnection(url);
		bm = BitmapFactory.decodeStream(net.getInStream());
		net.close();
		saveBmpToHardDisk(c, bm, toPath);
		return bm;
	}

	private static void saveBmpToHardDisk(Context c, Bitmap bm, String toPath) {
		if (bm == null) {
			LogUtlils.println("trying to savenull bitmap");
			return;
		}
		FileOutputStream outStream = null;
		File f = null;
		File dir = null;
		LogUtlils.println("---------toPath=" + toPath);
		try {
			f = new File(toPath);
			LogUtlils.println("getParent()=" + f.getParent());
			dir = new File(f.getParent());
			if (!dir.exists()) {
				dir.mkdirs();
			}
			// f = new File(toPath);
			// Boolean result = f.createNewFile();
			// LogUtlils.println("result="+result+"::f.canWrite()="+f.canWrite());
			// if (result && f.canWrite()) {
			outStream = new FileOutputStream(f);
			bm.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
			outStream.flush();
			outStream.close();
			LogUtlils.println("Image saved tosd");
			// } else {
			// LogUtlils.println("Image saved tosd fail");
			// }
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static String makeLocalAvatarPath(Context c, String fileName) {
		Boolean result = false;
		String fileNameResult = "";
		fileNameResult = getAvatarPath(c) + "/" + fileName;
		LogUtlils.println("fileNameResult==" + fileNameResult);

		return fileNameResult;
	}

	public static Bitmap makeAuthorAvatar(Context c, String path) {
		Bitmap bmp = null;
		if (!path.equals("")) {
			bmp = IOUtils.getBitmapFromFilePath(path);
		}
		if (bmp == null) {
			bmp = BitmapFactory.decodeResource(c.getResources(),
					R.drawable.posts_icon_unknown);
		}
		return bmp;
	}

	public static void delFile(String filepath) throws IOException {
		File f = new File(filepath);// 定义文件路径
		if (f.exists() && f.isDirectory()) {// 判断是文件还是目录
			if (f.listFiles().length == 0) {// 若目录下没有文件则直接删除
				f.delete();
			} else {// 若有则把文件放进数组，并判断是否有下级目录
				File delFile[] = f.listFiles();
				int i = f.listFiles().length;
				for (int j = 0; j < i; j++) {
					if (delFile[j].isDirectory()) {
						delFile(delFile[j].getAbsolutePath());// 递归调用del方法并取得子目录路径
					}
					delFile[j].delete();// 删除文件
				}
			}
		}
	}
}
